package mxmf.aop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import chances.smart.commons.mvc.interceptor.OpInfo;
import mxmf.entity.CmsEntity;

@Aspect
@Component
public class AuditAspect {
    public static final Logger logger = LoggerFactory.getLogger(AuditAspect.class);

    @Around("execution(* mxmf.ctrl..*.*(..)) ")
    @Order(1)
    public Object logAspect(ProceedingJoinPoint pjp) throws Throwable {
        Object[] params = pjp.getArgs();
        for (int i = 0; i < params.length; i++) {
            Object obj = params[i];
            if (CmsEntity.class.isInstance(obj)) {
                CmsEntity aAuditable = ((CmsEntity) obj);
                String userId = getUserId();
                aAuditable.setUpdaterId(userId);
                aAuditable.setUpdateTime(new Date());
            }
        }
        return pjp.proceed(pjp.getArgs());

    }

    /**
    private boolean isEntityAudit(JoinPoint jp, int index) {
        Signature signature = jp.getSignature();
    
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Annotation[] values = parameterAnnotations[index];
        for (Annotation value : values) {
            if (value instanceof CmsEntity) {
                return true;
            }
        }
        return false;
    
    }
    **/
    public String getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        OpInfo opInfo = (OpInfo) request.getAttribute("op_info");
        return opInfo != null ? opInfo.getLoginName() : null;
    }

}
